import django_filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics, pagination, status, filters, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import DeviceModel, CaseModel, CaseStepModel, StepResultModel, TestRunModel, SectionModel, ProjectModel, \
    AppiumConfigModel
from .serializers import DeviceSerializer, CaseSerializer, CaseStepSerializer, StepResultSerializer, TestRunSerializer, \
    TestRunCreateSerializer, SectionModelSerializer, ProjectSerializer, AppiumParameterSerializer


# ==========设备管理相关API================================================================

class StandardResultsSetPagination(pagination.PageNumberPagination):
    page_size = 10
    max_page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'page'


class DeviceListView(generics.ListCreateAPIView):
    queryset = DeviceModel.objects.all().order_by('id')  # 按 id 排序，确保一致
    serializer_class = DeviceSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['status', 'name', 'imei', 'udid']  # 精确匹配筛选字段
    search_fields = ['status', 'name', 'imei', 'udid']  # 支持模糊匹配的搜索字段

    def create(self, request, **kwargs):
        # 批量创建并返回创建成功和失败的列表
        data_list = []
        if not isinstance(request.data, list):
            data_list.append(request.data)
        else:
            data_list = request.data
        successful = []  # 保存成功的数据
        failed = []  # 跳过的数据及其原因
        for item in data_list:
            udid = item.get("udid")
            if item.get("imei") is None:
                item["imei"] = ''
            if DeviceModel.objects.filter(udid=udid).exists():
                # 如果 udid 已存在，记录失败信息
                failed.append({
                    "data": item,
                    "errors": f"设备 {udid} 已存在"
                })
            else:
                serializer = self.get_serializer(data=item)
                if serializer.is_valid():
                    self.perform_create(serializer)
                    successful.append(serializer.data)
                else:
                    failed.append({
                        "data": item,
                        "errors": serializer.errors
                    })

            # 返回部分成功的状态码及结果
        __result = {
            "successful": successful,
            "failed": failed
        }
        print(__result)
        return Response(
            __result,
            status=status.HTTP_207_MULTI_STATUS
        )

    def perform_create(self, serializer):
        serializer.save()


class DeviceRetrieveUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView):
    queryset = DeviceModel.objects.all()
    serializer_class = DeviceSerializer
    lookup_field = 'pk'


@api_view(['GET'])
def get_all_statuses(request):
    # 获取所有非空的 status，并去重
    statuses_list = DeviceModel.objects.values_list('status', flat=True).distinct()
    statuses = [sta for sta in statuses_list if sta]  # 排除空值
    return Response({"data": statuses})


# ==========设备管理相关API end================================================================
# ==========用例管理相关API================================================================
class CaseListsSetPagination(pagination.PageNumberPagination):
    page_size = 50
    max_page_size = 500
    page_size_query_param = 'pageSize'
    page_query_param = 'page'


def get_all_section_ids(section_id):
    """获取section_id所有子项"""

    def collect_ids(section):
        ids = [section.id]
        for child in section.subSections.all():
            ids.extend(collect_ids(child))
        return ids

    root_section = SectionModel.objects.get(id=section_id)
    return collect_ids(root_section)


class CaseFilter(django_filters.FilterSet):
    section_id = django_filters.BaseInFilter(method='filter_by_section')

    class Meta:
        model = CaseModel
        fields = ['section_id']

    def filter_by_section(self, queryset, name, value):
        all_section_ids = []
        for section_id in value:
            all_section_ids.extend(get_all_section_ids(section_id))
        return queryset.filter(section_id__in=all_section_ids)


class CaseViewSet(viewsets.ModelViewSet):
    queryset = CaseModel.objects.all().order_by('id')
    serializer_class = CaseSerializer

    # 使用django-filter以及自定义的CaseFilter过滤
    filter_backends = [DjangoFilterBackend]
    filterset_class = CaseFilter


class CaseStepViewSet(viewsets.ModelViewSet):
    queryset = CaseStepModel.objects.all().order_by('id')
    serializer_class = CaseStepSerializer


class SectionModelViewSet(viewsets.ModelViewSet):
    queryset = SectionModel.objects.all().order_by("id")
    serializer_class = SectionModelSerializer


class StepResultViewSet(viewsets.ModelViewSet):
    queryset = StepResultModel.objects.all().order_by("id")
    serializer_class = StepResultSerializer


class TestRunViewSet(viewsets.ModelViewSet):
    queryset = TestRunModel.objects.all().order_by("id")

    # serializer_class = TestRunSerializer

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return TestRunCreateSerializer
        return TestRunSerializer


# class SectionModelViewSet(viewsets.ModelViewSet):
#     queryset = SectionModel.objects.all().order_by("id")
#     serializer_class = SectionSerializer
class AppiumConfigViewSet(viewsets.ModelViewSet):
    queryset = AppiumConfigModel.objects.all().order_by("id")
    serializer_class = AppiumParameterSerializer


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = ProjectModel.objects.all().order_by("id")
    serializer_class = ProjectSerializer
